package cn.seaboot.admin.security.context;

import cn.seaboot.admin.user.context.AuthorityCache;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * 权限配置缓存
 * <p>
 * 会有两个不同的模块调用缓存:
 * 用户模块（配置模块），界面每次调整，都要及时清空缓存。
 * 鉴权模块（登录模块），为了避免频繁查询，会尝试写入缓存。
 *
 * @author Mr.css
 * @version 2023-07-10 9:47
 */
@Service
public class SecurityAntAuthorityCache implements AuthorityCache<GrantedAuthority, GrantedAuthority> {
    /**
     * 角色缓存
     */
    private final Map<String, Collection<GrantedAuthority>> roles = new HashMap<>();
    /**
     * 权限缓存
     */
    private final Map<String, Collection<GrantedAuthority>> permits = new HashMap<>();

    @Override
    public void putRoles(String key, Collection<GrantedAuthority> list) {
        roles.put(key, list);
    }

    @Override
    public void removeRoles(String key) {
        roles.remove(key);
    }

    @Override
    public Collection<GrantedAuthority> getRoles(String key) {
        return roles.get(key);
    }

    @Override
    public void putPermits(String key, Collection<GrantedAuthority> roles) {
        permits.put(key, roles);
    }

    @Override
    public void removePermits(String key) {
        permits.remove(key);
    }

    @Override
    public Collection<GrantedAuthority> getPermits(String key) {
        return permits.get(key);
    }

    @Override
    public void clear() {
        roles.clear();
        permits.clear();
    }
}
